﻿//
// Lightbox Gallery Module for DotNetNuke
// Project Contributors - Will Strohl (http://www.WillStrohl.com), Armand Datema (http://www.schwingsoft.com)
//
//Copyright (c) 2009-2013, Will Strohl
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are 
//permitted provided that the following conditions are met:
//
//Redistributions of source code must retain the above copyright notice, this list of 
//conditions and the following disclaimer.
//
//Redistributions in binary form must reproduce the above copyright notice, this list 
//of conditions and the following disclaimer in the documentation and/or other 
//materials provided with the distribution.
//
//Neither the name of Will Strohl, Armand Datema, Lightbox Gallery, nor the names of its contributors may be 
//used to endorse or promote products derived from this software without specific prior 
//written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
//EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
//OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
//SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
//TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
//BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
//CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
//DAMAGE.
//

//INSTANT C# NOTE: Formerly VB project-level imports:

using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Icons;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.FileSystem;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;

namespace WillStrohl.Modules.Lightbox
{

    public partial class ViewLightbox : WnsPortalModuleBase, IActionable
    {

        #region  Private Members

        private const string MENU_ITEM_TITLE_KEY = "EditLightbox.MenuItem.Title";
        private const string MENU_ITEM_CHANGEORDER_KEY = "EditLightbox.MenuItem.ChangeOrder";
        private const string CHANGE_ORDER = "ChangeOrder";
        private const string LIGHTBOX_KEY = "lightbox_clientscript";
        private const string ERROR_WRAP = "<div class=\"dnnFormMessage dnnFormValidationSummary\">{0}</span>";
        private const string EDIT_IMAGE_PATH = "/images/edit.gif";
        private const string ORDER_IMAGE_PATH = "/images/copy.gif";
        private const string IMAGE_TEMPLATE = "<li class=\"listitem\"><span class=\"wns_lightbox_span\"><a class=\"wns_lightbox_link\" rel=\"{0}\" href=\"{1}\" title=\"{3}\"><img src=\"{2}\" alt=\"{3}\" title=\"{3}\" class=\"wns_lightbox_image\" /></a></span></li> ";
        private const string IMAGE_EDIT_TEMPLATE = "<li class=\"listitem editview\"><span class=\"wns_lightbox_span\"><a class=\"wns_lightbox_link\" rel=\"{0}\" href=\"{1}\" title=\"{3}\"><img src=\"{2}\" alt=\"{3}\" title=\"{3}\" class=\"wns_lightbox_image\" /></a></span><span class=\"wns_lightbox_image_edit_wrap\"><a href=\"{4}\" class=\"wns_lightbox_image_edit\">{5}</a></span></li> ";
        private const int MAX_IMAGE_HEIGHT = 100;
        private const string TITLE_DESCRIPTION = "<strong>{0}</strong><br />{1}";

        private LightboxInfoCollection p_Albums = null;
        private List<int> p_AlbumIds = null;
        private string p_EditImage = Null.NullString;
        private string p_OrderImage = Null.NullString;
        private string p_DownloadImage = Null.NullString;

        #endregion

        #region  Private Properties

        private LightboxInfoCollection Albums
        {
            get
            {
                if (p_Albums == null)
                {
                    p_Albums = new LightboxInfoCollection();

                    var ctlLightbox = new LightboxController();

                    bool blnCount = ctlLightbox.DoesDisplayOrderNeedUpdate();
                    if (blnCount)
                    {
                        ctlLightbox.UpdateDisplayOrder();
                    }

                    if (GroupIdParam > Null.NullInteger)
                    {
                        // only grab albums for the current group page
                        try
                        {
                            p_Albums = (LightboxInfoCollection) (from l in ctlLightbox.GetLightboxes(ModuleId)
                                                                 where l.GroupId == GroupIdParam
                                                                 select l);
                        }
                        catch
                        {
                            // do nothing - there are no albums yet
                        }
                    }
                    else if (UserIdParam > Null.NullInteger)
                    {
                        // only grab albums for the current user profile
                        try
                        {
                            p_Albums = (LightboxInfoCollection)(from l in ctlLightbox.GetLightboxes(ModuleId)
                                                                where l.LastUpdatedBy == UserIdParam
                                                                select l);
                        }
                        catch
                        {
                            // do nothing - there are no albums yet
                        }
                    }
                    else
                    {
                        // grab all albums for this module
                        p_Albums = ctlLightbox.GetLightboxes(ModuleId);
                    }
                }

                return p_Albums;
            }
        }

        private List<int> AlbumIds
        {
            get
            {
                if (p_AlbumIds == null)
                {
                    //var ctlModule = new LightboxController();
                    //p_AlbumIds = new List<int>();
                    //p_AlbumIds = ctlModule.GetLightboxIds(ModuleId);
                    try
                    {
                        p_AlbumIds = (List<int>) (from a in Albums select a.LightboxId);
                    }
                    catch
                    {
                        // do nothing - there isn't a list to be parsed yet
                    }
                }

                return p_AlbumIds;
            }
        }

        protected string EditImage
        {
            get
            {
                if (!string.IsNullOrEmpty(p_EditImage))
                {
                    return p_EditImage;
                }

                var urlFormat = (Request.IsSecureConnection) ? "https://" : "http://";

                p_EditImage = string.Concat(urlFormat, PortalSettings.PortalAlias.HTTPAlias, IconController.IconURL("Edit", "16x16"));

                return p_EditImage;
            }
        }

        protected string OrderImage
        {
            get
            {
                if (!string.IsNullOrEmpty(p_OrderImage))
                {
                    return p_OrderImage;
                }

                var urlFormat = (Request.IsSecureConnection) ? "https://" : "http://";

                p_OrderImage = string.Concat(urlFormat, PortalSettings.PortalAlias.HTTPAlias, IconController.IconURL("Synchronize", "16x16"));

                return p_OrderImage;
            }
        }

        protected string DownloadImage
        {
            get
            {
                if (!string.IsNullOrEmpty(p_DownloadImage))
                {
                    return p_DownloadImage;
                }

                var urlFormat = (Request.IsSecureConnection) ? "https://" : "http://";

                p_DownloadImage = string.Concat(urlFormat, PortalSettings.PortalAlias.HTTPAlias, IconController.IconURL("Save", "16x16"));

                return p_DownloadImage;
            }
        }

        #endregion

        #region  Event Handlers

        /// <summary>
        /// OnInit - initialization of the module
        /// </summary>
        /// <param name="e"></param>
        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            //INSTANT C# NOTE: Converted event handler wireups:
            Load += new EventHandler(Page_Load);
            lnkNewAlbum.Click += new EventHandler(lnkNewAlbum_Click);
        }

        private void Page_Load(object sender, EventArgs e)
        {
            try
            {

                // only load the scripts if we need them (when there is 1 or more albums)
                if (Albums != null && Albums.Count > 0)
                {

                    // Load the Lightbox plugin client script on every page load
                    ClientResourceManager.RegisterScript(Page, string.Format(LightboxController.SCRIPT_TAG_FORMAT, string.Concat(ControlPath, "js/fancybox/jquery.fancybox-1.3.4.pack.js")));
                    
                    // Load the Lightbox plugin CSS
                    ClientResourceManager.RegisterStyleSheet(Page, string.Concat(ControlPath, "js/fancybox/jquery.fancybox-1.3.4.css"));
                    
                }

                if (!Page.IsPostBack)
                {
                    BindData();
                }

            }
            catch (Exception exc) // Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc, IsEditable);
            }
        }

        protected void lnkNewAlbum_Click(object sender, EventArgs e)
        {
            Response.Redirect(GetEditUrl());
        }

        #endregion

        #region  Helper Methods

        private void BindData()
        {
            LocalizeModule();

            rptGallery.Visible = false;

            pnlButton.Visible = IsInSocialMode();

            if (Albums != null && Albums.Count > 0)
            {
                rptGallery.DataSource = Albums;
                rptGallery.DataBind();
                rptGallery.Visible = true;

                WriteOutLightboxConstructors();
            }
            else
            {
                Skin.AddModuleMessage(this, GetLocalizedString("Error.NoAlbums"), ModuleMessage.ModuleMessageType.BlueInfo);
            }

        }

        private void LocalizeModule()
        {
            lnkNewAlbum.Text = GetLocalizedString("EditLightbox.MenuItem.Title");
        }

        protected string GetImageFiles(string LightboxId, string FolderName, string GalleryName)
		{

			string strReturn = string.Empty;

			if (Regex.IsMatch(FolderName, LightboxController.FOLDER_NAME_MATCH_PATTERN))
			{
				FolderName = Regex.Replace(FolderName, LightboxController.FOLDER_NAME_REPLACE_PATTERN, LightboxController.FOLDER_NAME_REPLACEMENT_PATTERN);
			}

			if (FolderManager.Instance.FolderExists(PortalId, FolderName))
			{

				int intLightboxId = int.Parse(LightboxId, NumberStyles.Integer);
				ArrayList arrImages = null;

				// grab a list of only images from the directory (folder)
				var oFolder = FolderManager.Instance.GetFolder(PortalId, FolderName);
				arrImages = LightboxController.VerifiedFileList(FolderManager.Instance.GetFiles(oFolder, true));

				// create a thumbnail for each image
				CreateThumbnails(arrImages);

				// delete any references to missing/deleted files
				SyncImagesWithDatabase(intLightboxId, arrImages);

				if (arrImages.Count > 0)
				{

					var ctlModule = new LightboxController();
					var oLightbox = ctlModule.GetLightbox(intLightboxId);
					var sb = new StringBuilder(50);

					sb.AppendFormat("<ul id=\"{0}\" class=\"wns_lightbox\">", GetGalleryListId(GalleryName));

					// create the image tiles
					foreach(IFileInfo oImage in arrImages)
					{

						if (! (string.IsNullOrEmpty(oImage.FileName)))
						{

							string imgFileName = GetFileName(oImage.FileName);

							// attempt to get a reference to the image
							ImageInfo img = ctlModule.GetImageByFileName(intLightboxId, imgFileName);

							if (img == null)
							{
								// create a reference to the image
								ctlModule.AddImage(intLightboxId, imgFileName, imgFileName, string.Empty, 0, UserId);
								// reload the reference
								img = ctlModule.GetImageByFileName(intLightboxId, imgFileName);
							}

						}
					}

					// get a collection of the images to display
					ImageInfoCollection collImage = ctlModule.GetImages(intLightboxId);
					IFolderInfo oLightboxFolder = FolderManager.Instance.GetFolder(PortalId, oLightbox.GalleryFolder);

					foreach(ImageInfo objImage in collImage)
					{

						IFileInfo oImage = ctlModule.GetImageFromProvider(PortalId, oLightboxFolder, objImage.FileName);
						IFileInfo oImageThumbnail = ctlModule.GetImageFromProvider(PortalId, oLightboxFolder, LightboxController.GetThumbnailImageName(objImage.FileName, PortalSettings, true));

                        if (oImage != null && string.Equals(objImage.FileName.ToLower(), "spacer.gif") == false)
					    {

					        var fullImageUrl = GetImageFileUrl(oImage);

					        // generate a title
					        var title = objImage.Title;

					        // include the description if it's there
					        if (!string.IsNullOrEmpty(objImage.Description))
					        {
					            title = string.Format(TITLE_DESCRIPTION, title, objImage.Description);
					        }

					        // generate the thumbnail markup
					        if (IsEditable && PortalSettings.UserMode == PortalSettings.Mode.Edit)
					        {
					            sb.AppendFormat(IMAGE_EDIT_TEMPLATE, CleanNameForRel(GalleryName), fullImageUrl,
					                            GetImageFileUrl(oImageThumbnail), title, GetImageEditUrl(objImage),
					                            GetLocalizedString("ImageEdit.Text"));
					        }
					        else
					        {
					            sb.AppendFormat(IMAGE_TEMPLATE, CleanNameForRel(GalleryName), fullImageUrl,
					                            GetImageFileUrl(oImageThumbnail), title);
					        }

					    }

					}

					sb.Append("</ul>");

					strReturn = sb.ToString();
				}
				else
				{
					strReturn = string.Format(ERROR_WRAP, GetLocalizedString("Error.NoImagesFound"));
				}
			}
			else
			{
				if (IsEditable)
				{
					strReturn = string.Format(ERROR_WRAP, GetLocalizedString("Error.PathNotFound"));
					strReturn = string.Format(strReturn, FolderName);
				}
				else
				{
					strReturn = string.Format(ERROR_WRAP, GetLocalizedString("Error.PathNotFound.Anonymous"));
				}
			}

			return strReturn;
		}

        private void SyncImagesWithDatabase(int LightboxId, ArrayList FilesOnServer)
		{

			var arrFilesOnServer = new ArrayList();

			// prepare a list of the valid files in the filesystem
			foreach(IFileInfo strFile in FilesOnServer)
			{
				if (! (string.IsNullOrEmpty(strFile.FileName)))
				{
					arrFilesOnServer.Add(GetFileName(strFile.FileName));
				}
			}

			var ctlLightbox = new LightboxController();
			var collImagesInDb = ctlLightbox.GetImages(LightboxId);

			if (collImagesInDb != null && collImagesInDb.Count > 0)
			{

				// iterate through the DB image list
				var arrFilesInDatabase = new ArrayList();
				foreach(ImageInfo oImageInDb in collImagesInDb)
				{

					arrFilesInDatabase.Add(oImageInDb.FileName);

				} // For Each oImageInDb As ImageInfo In collImagesInDb

				// determine which files are orphaned
				ArrayList arrDifference = GetOrphanedFiles(arrFilesInDatabase, ref arrFilesOnServer);

				if (arrDifference != null)
				{

					foreach(string strFile in arrDifference)
					{

						LightboxInfo oLightbox = ctlLightbox.GetLightbox(LightboxId);
						ImageInfo oImage = ctlLightbox.GetImageByFileName(LightboxId, strFile);

						// need to get the thumbnail file name
						string strThumbnail = LightboxController.GetThumbnailImageName(oImage.FileName, PortalSettings, false);

						// need to map to the file
						if (! (Regex.IsMatch(strThumbnail, "[/\\\\]+", RegexOptions.IgnoreCase)))
						{
							strThumbnail = string.Concat(PortalSettings.HomeDirectoryMapPath, oLightbox.GalleryFolder, strThumbnail);
							strThumbnail = LightboxController.ReformatPathForLocal(strThumbnail);
						}

						IFolderInfo oFolder = FolderManager.Instance.GetFolder(PortalId, oLightbox.GalleryFolder);

						if (FileManager.Instance.FileExists(oFolder, strThumbnail))
						{
							try
							{
								// delete the thumbnail
								IFileInfo oFile = ctlLightbox.GetImageFromProvider(PortalId, oFolder, strThumbnail);
								FileManager.Instance.DeleteFile(oFile);
							}
							catch (Exception ex)
							{
								Exceptions.LogException(ex);
							}
						}

						// drop from the database
						ctlLightbox.DeleteImageById(oImage.ImageId);

					}

				}

			} // If Not collImagesInDb Is Nothing AndAlso collImagesInDb.Count > 0 Then

		}

        private ArrayList GetOrphanedFiles(ArrayList FilesOnDatabase, ref ArrayList FilesOnServer)
		{

			var arrDifference = new ArrayList();

			foreach(string item in FilesOnDatabase)
			{
				if (! (FilesOnServer.Contains(item)))
				{
					arrDifference.Add(item);
				}
			}

			return arrDifference;

		}

        private void CreateThumbnails(ArrayList Files)
		{

			Image oImage = null;
			Image oThumbnail = null;

			foreach(IFileInfo oFile in Files)
			{

				// only proceed if this is a real file name, and the file name doesn't already exist
				if (! (string.IsNullOrEmpty(oFile.FileName)) && ! (Regex.IsMatch(oFile.FileName, LightboxController.THUMBNAIL_MATCH_PATTERN, RegexOptions.IgnoreCase)))
				{

					// only create a thumbnail if it doesn't exist
					string strThumbnailFileName = LightboxController.GetThumbnailImageName(oFile.FileName, PortalSettings, false);
					IFolderInfo oFolder = FolderManager.Instance.GetFolder(PortalId, oFile.Folder);

					if (! (FileManager.Instance.FileExists(oFolder, strThumbnailFileName)))
					{

						try
						{
							// get an instance of the image
							oImage = Image.FromStream(FileManager.Instance.GetFileContent(oFile));
						}
						catch (Exception ex)
						{
							Exceptions.LogException(ex);
						}

						if (oImage != null)
						{
							int intNewWidth = 100;

							if (oImage.Width <= intNewWidth)
							{
								intNewWidth = oImage.Width;
							}

							int intNewHeight = Convert.ToInt32(oImage.Height * intNewWidth / (double)oImage.Width);

							if (intNewHeight > MAX_IMAGE_HEIGHT)
							{
								intNewWidth = Convert.ToInt32(oImage.Width * MAX_IMAGE_HEIGHT / (double)oImage.Height);
								intNewHeight = MAX_IMAGE_HEIGHT;
							}

							// create and save a thumbnail
							oThumbnail = oImage.GetThumbnailImage(intNewWidth, intNewHeight, null, IntPtr.Zero);

							// save the image in memory
							var ms = new MemoryStream();

							// branch the save statement to avoid encoder errors
							switch (oFile.Extension.ToLower())
							{
								case "jpg":
									oThumbnail.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
									break;
								case "gif":
									oThumbnail.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
									break;
								case "png":
									oThumbnail.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
									break;
							}

							// save the image in the DNN file system
							FileManager.Instance.AddFile(oFolder, strThumbnailFileName, ms);
						}

					} // If Not File.Exists(ThumbnailImageName(oFile)) Then

				} // If Not String.IsNullOrEmpty(oFile) Then

			}

		}

        /// <summary>
        /// WriteOutLightboxConstructors - builds the JS constructors to add to the page for the fancybox plugin
        /// </summary>
        /// <remarks></remarks>
        /// <history>
        /// 20101013 - wstrohl - Added newlines to prevent javascript errors
        /// </history>
        private void WriteOutLightboxConstructors()
		{

			if (AlbumIds != null)
			{

				var ctlLightbox = new LightboxController();
				var objAlbum = new LightboxInfo();
				var objSetting = new SettingInfo();
				var sb = new StringBuilder(500);
				string strUlId = Null.NullString;

				sb.Append("<script type=\"text/javascript\" language=\"javascript\">");
				sb.Append(Environment.NewLine);
				sb.Append("jQuery(document).ready(function (){ ");
				sb.Append(Environment.NewLine);

				foreach(int intI in AlbumIds)
				{
					objAlbum = new LightboxInfo();
					objAlbum = ctlLightbox.GetLightbox(intI);
					objSetting = ctlLightbox.GetSettings(objAlbum.LightboxId);

					strUlId = GetGalleryListId(objAlbum.GalleryName);


					sb.AppendFormat("jQuery('ul#{0} li span a.wns_lightbox_link').fancybox(", strUlId);
					sb.Append(" { ");

					sb.AppendFormat("'changeSpeed': {0}, ", objSetting.ChangeSpeed);
					sb.AppendFormat("'cyclic': {0}, ", objSetting.Cyclic.ToString().ToLower());
					sb.AppendFormat("'enableEscapeButton': {0}, ", objSetting.EnableEscapeButton.ToString().ToLower());
					sb.AppendFormat("'margin': {0}, ", objSetting.Margin);
					sb.AppendFormat("'modal': {0}, ", objSetting.Modal.ToString().ToLower());
					if (! (string.IsNullOrEmpty(objSetting.OnCancel)))
					{
						sb.AppendFormat("'onCancel': {0}, ", objSetting.OnCancel);
					}
					if (! (string.IsNullOrEmpty(objSetting.OnCancel)))
					{
						sb.AppendFormat("'onCancel': {0}, ", objSetting.OnCleanup);
					}
					if (! (string.IsNullOrEmpty(objSetting.OnClosed)))
					{
						sb.AppendFormat("'onClosed': {0}, ", objSetting.OnClosed);
					}
					if (! (string.IsNullOrEmpty(objSetting.OnComplete)))
					{
						sb.AppendFormat("'onComplete': {0}, ", objSetting.OnComplete);
					}
					if (! (string.IsNullOrEmpty(objSetting.OnStart)))
					{
						sb.AppendFormat("'onState': {0}, ", objSetting.OnStart);
					}
					sb.AppendFormat("'opacity': {0}, ", objSetting.Opacity.ToString().ToLower());
					sb.AppendFormat("'overlayColor': '{0}', ", objSetting.OverlayColor);
						//
						// This update has been made per 'codedude'
						// Issue: http://wnslightbox.codeplex.com/workitem/4605
						// Ref: http://wnslightbox.codeplex.com/Thread/View.aspx?ThreadId=208034
						//.AppendFormat("'overlayOpacity': {0}, ", objSetting.OverlayOpacity)
					sb.AppendFormat("'overlayOpacity': {0}, ", objSetting.OverlayOpacity.ToString().Replace(",", "."));
						//
					sb.AppendFormat("'overlayShow': {0}, ", objSetting.OverlayShow.ToString().ToLower());
					sb.AppendFormat("'padding': {0}, ", objSetting.Padding);
					sb.AppendFormat("'showCloseButton': {0}, ", objSetting.ShowCloseButton.ToString().ToLower());
					sb.AppendFormat("'showNavArrows': {0}, ", objSetting.ShowNavArrows.ToString().ToLower());
					sb.AppendFormat("'speedIn': {0}, ", objSetting.Speed.ToString().ToLower());
					sb.AppendFormat("'speedOut': {0}, ", objSetting.Speed.ToString().ToLower());
					sb.AppendFormat("'titlePosition': '{0}', ", objSetting.TitlePosition.ToString().ToLower());
					sb.AppendFormat("'titleShow': {0}, ", objSetting.TitleShow.ToString().ToLower());
					sb.AppendFormat("'transitionIn': '{0}', ", objSetting.Transition);
					sb.AppendFormat("'transitionOut': '{0}' ", objSetting.Transition);

					sb.Append(" } );");
					sb.Append(Environment.NewLine);

					if (objAlbum.HideTitleDescription)
					{
						sb.AppendFormat("jQuery('#h3-{0}-{1}, #p-{0}-{1}').remove();", TabModuleId, objAlbum.LightboxId);
						sb.Append(Environment.NewLine);
					}

				}

				sb.Append(" } );");
				sb.Append(Environment.NewLine);
				sb.Append("</script>");
				sb.Append(Environment.NewLine);

				phScript.Controls.Add(new LiteralControl(sb.ToString()));
				
			} // If Not Me.p_AlbumIds Is Nothing Then

		}

        private string GetGalleryListId(string GalleryName)
        {
            return string.Format("ul{0}_{1}", CleanNameForRel(GalleryName), ModuleId);
        }

        private string GetFileName(string FilePath)
        {

            return Path.GetFileName(FilePath);

        }
        
        #endregion

        #region  URL Helper Methods
        
        private string GetImageFileUrl(IFileInfo Image)
        {

            try
            {
                var ctlModule = new LightboxController();
                return ctlModule.GetImageFileUrl(Image);
            }
            catch (Exception ex)
            {
                if (IsEditable && PortalSettings.UserMode == PortalSettings.Mode.Edit)
                {
                    Exceptions.ProcessModuleLoadException(this, ex, true);
                }
                else
                {
                    Exceptions.LogException(ex);
                }
                return string.Empty;
            }

        }

        #endregion

        #region  Clean Helper Methods

        protected string CleanNameForRel(object AlbumName)
        {
            if (AlbumName != null)
            {
                return CleanNameForRel(AlbumName.ToString());
            }
            else
            {
                return string.Empty;
            }
        }

        protected string CleanNameForRel(string AlbumName)
        {
            if (!(string.IsNullOrEmpty(AlbumName)))
            {
                // remove any non-alphanumeric characters from the GalleryName, and append to create a stand-alone lightbox album
                return string.Concat("lightbox-", Regex.Replace(AlbumName, "\\W", string.Empty));
            }
            else
            {
                return string.Empty;
            }
        }

        private string CleanForClientScript(string Text)
        {
            return Regex.Replace(Text, "'", "\\'");
        }

        #endregion

        #region  IActionable Implementation

        public ModuleActionCollection ModuleActions
        {
            get
            {
                var Actions = new ModuleActionCollection();

                // add the default edit link to add a new album
                Actions.Add(GetNextActionID(), 
                    GetLocalizedString(MENU_ITEM_TITLE_KEY), 
                    string.Empty, 
                    string.Empty, 
                    string.Empty, 
                    GetEditUrl(), 
                    false, 
                    SecurityAccessLevel.Edit, 
                    true, 
                    false);

                // if there is more than one album, allow the change order view to be displayed

                var ctlModule = new LightboxController();
                int intCount = ctlModule.GetLightboxCount(ModuleId);

                if (intCount > 1)
                {

                    // add an edit link to allow the album display order to be updated
                    Actions.Add(GetNextActionID(), 
                        GetLocalizedString(MENU_ITEM_CHANGEORDER_KEY), 
                        string.Empty, 
                        string.Empty, 
                        string.Empty, 
                        GetEditUrl(CHANGE_ORDER), 
                        false, 
                        SecurityAccessLevel.Edit, 
                        true, 
                        false);

                }

                return Actions;
            }
        }

        #endregion
        
    }

}